% define f
f = [3 3 3 3 3 2 2 2 2 2 3 3 3 3 3;
3 3 1 2 1 0 0 0 0 0 1 2 3 3 3;
3 3 2 0 0 0 0 0 0 0 0 0 2 3 3;
3 2 0 0 1 0 0 0 0 0 1 0 0 2 3;
3 1 0 2 3 1 0 0 0 3 3 1 0 1 3;
2 0 0 3 3 2 0 0 1 3 3 2 0 0 2;
2 0 0 2 3 1 0 0 0 2 3 1 0 0 2;
2 0 0 0 0 0 0 0 0 0 0 0 0 0 2;
2 0 0 0 0 0 0 0 0 0 0 0 0 0 2;
2 0 1 2 1 1 0 0 0 1 1 2 2 0 2;
3 1 0 2 3 3 3 3 3 3 3 3 0 1 3;
3 2 0 0 2 3 3 3 3 3 2 0 0 2 3;
3 3 2 0 0 2 3 3 3 2 0 0 2 3 3;
3 3 3 2 1 0 0 0 0 0 1 2 3 3 3;
3 3 3 3 3 2 2 2 2 2 3 3 3 3 3];

% to get g, iterate all the elements in f
[m, n] = size(f);
g = zeros(m, n); % create a zero matrix

for i = 1:m
    for j = 1:n
        % set all the element that greater than 1 to 1
        if f(i, j) > 1
                g(i, j) = 1; 
        % set others(smaller or equal to 1) to 0
        else
                g(i, j) = 0; 
        end
    end
end

disp(g);

% use bwlabel to label the 8-connected components in this image
labeledImage = bwlabel(g, 8);
[labels, numLabels] = custom_bwlabel(g);

disp(labels);
disp(labeledImage);


% display
figure;
imshow(label2rgb(labels, 'hsv', 'k', 'shuffle'));
title('Connected Components');
